package com.example.demo.utils;

import com.example.demo.entity.User;
import com.example.demo.enums.Role;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class EntityUtils {
    public static void transEmptyToNull(Object o) throws IllegalAccessException {
        Field[] fields = o.getClass().getDeclaredFields();
        for(Field field :fields){
            Class<?> cl = field.getType();
            if(cl==String.class){
                field.setAccessible(true);
                String str = (String)field.get(o);
                if(str.equals("")){
                    field.set(o, null);
                }
            }
        }
    }

    private static String[] getNullPropertyNames(Object source) {
        Class<?> clz = source.getClass();
        Field[] fields = clz.getDeclaredFields();
        List<String> propertyNames = new ArrayList<>();
        for(Field field : fields) {
            field.setAccessible(true);
            try {
                if(null == field.get(source))
                    propertyNames.add(field.getName());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return propertyNames.toArray(new String[]{});
    }

    public static <T> T copyProperties(T src, T target, boolean ignoreNull) {
        if (ignoreNull) {
            BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
        } else {
            BeanUtils.copyProperties(src, target);
        }
        return target;
    }

    public static void main(String[] args) throws IllegalAccessException {
        User user = new User("", "", "", "", "", "", Role.USER, "", "", "", "");
        EntityUtils.transEmptyToNull(user);
        System.out.println(user);
        System.out.println(user.getId()==null);
        System.out.println(user.getRole()==null);
    }
}
